package controller;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import po.User;
import service.UserService;

@Controller
public class AnnotationController {

	@Autowired
	UserService userService;
	
	@RequestMapping(value="show.action")
	public String show(ModelMap model){
		
		User user = userService.selectById(1l);
		model.addAttribute("name", user.getName());
		return "index";
	}
	
	@RequestMapping(value="redirect.action")
	public String redirect(ModelMap model){
		
		model.addAttribute("name", "涂有");
		return "redirect:/index.jsp";
	}
	
	@RequestMapping("forward.action")
	public String forward(ModelMap model){
		
		model.addAttribute("name", "涂有");
		return "forward:/index.jsp";
	}
	
	@RequestMapping(value="request.action")
	public String request(HttpServletRequest request,
			HttpServletResponse response, 
			ModelMap model, 
			@RequestParam(value="name", defaultValue="杨瑞") String name){
		
		model.addAttribute("name", request.getParameter("name"));
		return "index";
	}
	
	@RequestMapping(value="name.action")
	public String name(ModelMap model, 
			@RequestParam(value="name", defaultValue="杨瑞") String name){
		
		model.addAttribute("name", name);
		return "index";
	}
	
	@RequestMapping(value="body.action")
	@ResponseBody
	public String body(ModelMap model){
		
		return "asdfasdfsadfsadfsdf";
	}
	
	@RequestMapping("array.action")
	@ResponseBody
	public String array(String[] name){
		
		return Arrays.toString(name);
	}
	
	@RequestMapping("pojo.action")
	@ResponseBody
	public String pojo(User user){
		
		return user.toString();
	}
	
	@RequestMapping("jsonRequest.action")
	@ResponseBody
	public String jsonRequest(@RequestBody User user){
		
		return user.toString();
	}
	
	@RequestMapping("valid.action")
	public void valid(HttpServletResponse response, 
			@RequestBody @Valid User user, 
			BindingResult result) throws IOException{
		
		StringBuffer sb = new StringBuffer();
		for(ObjectError error : result.getAllErrors()){
			
			sb.append(error.getDefaultMessage() + "；");
		}
		
		response.setHeader("content-type", "application/json; charset=utf-8");
		response.getWriter().println(sb.toString());
	}
}
